//
//  HJCHomeCell.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/17.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit
import SDWebImage

protocol HJCHomeCellDelegate : NSObjectProtocol{
    //哪个cell。的第几张图片
    func homeCellDidClickPhoto(cell:HJCHomeCell,index:Int)
}

class HJCHomeCell: UITableViewCell {
    
    
    
    @IBOutlet weak var iconView: UIImageView!  //头像
    
    @IBOutlet weak var nameLbl: UILabel!  //用户昵称
    
    @IBOutlet weak var timeLbl: UILabel!  //时间

    @IBOutlet weak var source: UILabel!  //来源
    
    @IBOutlet weak var textLbl: UILabel! //正文
    
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var pictureView: UICollectionView!
    
    @IBOutlet weak var collectionViewWidth: NSLayoutConstraint!
    
    @IBOutlet weak var bottomView: UIView!
    
    @IBOutlet weak var retweetedText: UILabel!
    
    @IBOutlet weak var repostsBtn: UIButton!
    
    @IBOutlet weak var commentsBtn: UIButton!
    
    //代理属性
    var photoDelegate : HJCHomeCellDelegate?
    
    //微博模型
    var status : HJCStatus?{
        //赋值
        didSet{
            nameLbl.text = status?.user?.name
            timeLbl.text = NSDate.createDate(status!.created_at!)?.fullDescription() ?? ""
            source.text = (status?.source?.hrefLink())?.linkText ?? ""
            textLbl.attributedText = Emoticon.emoticonString(status!.text!, lineHeight:17)
            if status?.reposts_count > 0{
                repostsBtn.setTitle("\(status!.reposts_count)", forState: UIControlState.Normal)
            }else {
                repostsBtn.setTitle("转发", forState: UIControlState.Normal)
            }
            if status?.comments_count>0{
                commentsBtn.setTitle("\(status!.comments_count)", forState: UIControlState.Normal)
            }else{
                commentsBtn.setTitle("评论", forState: UIControlState.Normal)
            }
            if  let urlStr = status?.user?.profile_image_url {
                let url = NSURL(string: urlStr)!
                iconView.sd_setImageWithURL(url)
            }
            
            //设置collectionView的大小
            setCollectionViewSize(status)
            //刷配图数据
            pictureView.reloadData()
            
            //设置转发正文
            if status?.retweeted_status != nil{
                if   status?.retweeted_status?.user?.name != nil{
                    retweetedText!.attributedText = Emoticon.emoticonString("@"+"\(status!.retweeted_status!.user!.name!)" + ":"+"\(status!.retweeted_status!.text!)", lineHeight:17)
                }else{
                     retweetedText!.attributedText = Emoticon.emoticonString(status!.retweeted_status!.text!, lineHeight:17)
                }
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        //设置正文的最大宽度
        textLbl.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
        
            retweetedText?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
    
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    ///设置collectionView的size
    func setCollectionViewSize(status:HJCStatus?){
        //计算出collecttionView的大小
        let collecttionSize = collectionViewSize(status)
        //设置collecttionView的约束
        collectionViewHeight.constant = collecttionSize.height
        collectionViewWidth.constant = collecttionSize.width
        //设置itemsize的大小
        if status?.weiboPic_urls?.count == 1{
           flowLayout.itemSize = collecttionSize
        }else{
            flowLayout.itemSize = CGSizeMake(90, 90)
        }
        //设置最小间距
        flowLayout.minimumInteritemSpacing = 5
        flowLayout.minimumLineSpacing = 5
        //更新约束(这里是在layoutsubviews之前执行，不需要更新，假如填写了，会造成页面卡顿)
//        self.layoutIfNeeded()
    }
    ///计算collectionView的size
    func collectionViewSize(status:HJCStatus?)->(CGSize){
        
        //定义图片的尺寸
        let w : CGFloat = 90;
        let h : CGFloat = 90;
        //间隙
        let margin : CGFloat = 5;
        
        let imageCount = status!.weiboPic_urls?.count ?? 0
        
        //如果只有0张配图
        if imageCount == 0{
            return CGSize.zeroSize
        }
        
        //当只有一张图片的时候，保持图片比例
        if imageCount == 1{
            //从缓存中提取图片
            let pictureDic = status!.weiboPic_urls![0]
            let pictureStr = pictureDic["thumbnail_pic"] as! String
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(pictureStr)
            if image == nil{
                return CGSizeZero
            }
            //返回图片尺寸
            return image.size
        }
        //如果有4张配图，就是2*2格式
        if imageCount == 4{
            return CGSizeMake(w*2+margin, h*2+margin)
        }
        
        //来到这就就是3*3格式的了
        let row = CGFloat((imageCount-1)/3) + 1
        
        return CGSizeMake(w*3+2*margin, h*row+margin*(row - 1))
    }
    
    ///返回cell的identifier
    class func identifierOfcell(status:HJCStatus)->(String){
        
        if status.retweeted_status == nil {
            return "homeCell"
        }
        return "retweetedCell"
    }
   
    
    ///返回cell的高度
    func heightForCell(status:HJCStatus)->(CGFloat){
        
        //设置微博数据
        self.status = status
        //刷新布局
        self.layoutIfNeeded()
        //返回高度
        return  CGRectGetMaxY(bottomView.frame)
    }

}



///MARK: - UICollectionViewDataSource
extension HJCHomeCell : UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        return status?.weiboPic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //取出可重用的cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imagecell", forIndexPath: indexPath) as! HJCPicturesCell
       //取出照片字典
        let picturesdict = status!.weiboPic_urls![indexPath.item]
        //取出照片url路径
        let pictureUrlStr = picturesdict["thumbnail_pic"] as! String
        //赋值
        cell.urlStr = pictureUrlStr
        //返回
        return cell
        
    }
    ///选中item的时候调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //通知home控制器跳转到照片浏览器
        photoDelegate?.homeCellDidClickPhoto(self, index: indexPath.item)
        
    }
    

}
